<template>
  <div>
    <n-drawer :width="drawerWidth" v-model:show="props.exportJianYingShow" :on-after-enter="getStoryBoardView">
      <n-drawer-content title="剪映导出"  >
        <n-grid :x-gap="10">
          <n-grid-item :span="8">
            <n-scrollbar :style="{ height: clientHeight - (layoutHeaderHeight  + tabsHeight + 133) + 'px'}">
              <n-form   label-placement="top" label-width="100" label-align="left">
                <n-alert type="warning" style="margin-bottom:10px;">导出剪映草稿之前,请先关闭剪映软件！</n-alert>
                <n-form-item label="故事名称"  v-if="storyBoardView">
                  <n-input v-model:value="storyBoardView.storyName"></n-input>
                </n-form-item>

                <n-grid :cols="2" :x-gap="24" v-if="storyBoardView?.voicePlanType">
                  <n-form-item-gi label="音频方案">
                    <n-select disabled :options="planOptions" v-model:value="storyBoardView.voicePlanType"></n-select>
                    <n-button v-if="storyBoardView.voiceUserFileId && storyBoardView.voicePlanType != 'systemVoice'" style="margin-left: 2px;" @click="audioWholePlay(storyBoardView.voiceUserFileId)" type="primary">播放</n-button>
                  </n-form-item-gi>
                  <n-form-item-gi label="类型">
                    <n-select disabled :options="articleType" v-model:value="storyBoardView.storyType"></n-select>
                  </n-form-item-gi>
                </n-grid>
<!--                <n-form-item label="导出方式">-->
<!--                  <n-input v-model:value="jianYingDraftPath"></n-input>-->
<!--                </n-form-item>-->
                <n-form-item label="剪映草稿位置 (在环境设置中设置)">
                  <n-input v-model:value="jianYingDraftPath" disabled></n-input>
                </n-form-item>
                <n-form-item label="关键帧方向">
                  <n-radio-group v-model:value="exportJianYingForm.type">
                    <n-radio value="2">上下</n-radio>
                    <n-radio value="1">左右</n-radio>
                    <n-radio value="3">缩放</n-radio>
                    <n-radio value="4">随机</n-radio>
                  </n-radio-group>
                </n-form-item>

                <n-grid :x-gap="2" :cols="3">
                  <n-grid-item>
                    <n-form-item label="缩放倍数" label-placement="top">
                      <n-input-number v-model:value="exportJianYingForm.scale" :show-button="false">
                        <template #suffix>
                          %
                        </template>
                      </n-input-number>
                    </n-form-item>
                  </n-grid-item>

                  <n-grid-item v-if="exportJianYingForm.type==='1' || exportJianYingForm.type==='4'" >
                    <n-form-item label="左起始位置" label-placement="top">
                      <n-input-number
                        :show-button="false"
                        v-model:value="exportJianYingForm.startLeft">
                      </n-input-number>
                    </n-form-item>
                  </n-grid-item>

                  <n-grid-item v-if="exportJianYingForm.type==='1' || exportJianYingForm.type==='4'">
                    <n-form-item label="右结束位置" label-placement="top">
                      <n-input-number
                        :show-button="false"
                        v-model:value="exportJianYingForm.endRight">
                      </n-input-number>
                    </n-form-item>
                  </n-grid-item>

                  <n-grid-item v-if="exportJianYingForm.type==='2' || exportJianYingForm.type==='4'" >
                    <n-form-item label="上起始位置" label-placement="top">
                      <n-input-number
                        :show-button="false"
                        v-model:value="exportJianYingForm.startBottom">
                      </n-input-number>
                    </n-form-item>
                  </n-grid-item>

                  <n-grid-item v-if="exportJianYingForm.type==='2' || exportJianYingForm.type==='4'" >
                    <n-form-item label="下结束位置" label-placement="top">
                      <n-input-number
                        :show-button="false"
                        v-model:value="exportJianYingForm.endTop">
                      </n-input-number>
                    </n-form-item>
                  </n-grid-item>
                </n-grid>
              </n-form>
            </n-scrollbar>

            <audio ref="audioPlayer" controls style="width: 100%">
              <source :src="mp3Url" type="audio/mpeg">
            </audio>
          </n-grid-item>

          <n-grid-item :span="16">
            <n-grid :x-gap="10">
              <n-grid-item :span="6">
                <n-form-item :show-label="false">
                  <n-select :options="statusOptions" v-model:value="statusOption" @update:value="statusSelected"></n-select>
                </n-form-item>
              </n-grid-item>
              <n-grid-item :span="18">
                <n-h3 v-if="storyBoardView?.storyBoardViews">
                  共 <n-text type="info">{{staticData.totalNum}}</n-text> 个分镜
                  ( 已完成 <n-text type="primary">{{staticData.successNum}}</n-text> /
                  未完成 <n-text type="error"> {{staticData.failNum}}</n-text> )
                </n-h3>
              </n-grid-item>
            </n-grid>
            <n-scrollbar :style="{ height: clientHeight - (layoutHeaderHeight  + tabsHeight + 130) + 'px'}" trigger="none">
              <n-spin   :show="queryLoading" v-if="queryLoading">
                <n-alert :style="{ height: clientHeight - (layoutHeaderHeight  + tabsHeight + 130) + 'px'}"  >
                </n-alert>
              </n-spin>
              <n-grid :x-gap="2" :y-gap="2" v-else>
                  <n-grid-item :span="6" v-if="storyBoardView?.storyBoardViews" v-for="boardView in storyBoardView?.storyBoardViews">
                    <n-card :header-style="{padding: '5px 5px 5px 5px'}" :content-style="{padding: '2px 2px 2px 2px'}" >
                      <template #cover>
                        <n-image
                          v-if="boardView.imageUserFileId"
                          :object-fit="'scale-down'"
                          :src="fileFunction.getViewFilePathByUserFileId(boardView.imageUserFileId)"></n-image>
                        <n-empty
                          v-else
                          size="large" description="还未生成"
                          style="height: 150px">
                        </n-empty>
                      </template>
                      <n-row>
                        <n-col :span="6"> ({{boardView.orderNum}})</n-col>
                        <n-col :span="6" v-if="storyBoardView.voicePlanType == 'systemVoice'">
                          <n-icon size="20" v-if="boardView.voiceUserFileId" @click="audioPlay(boardView)">
                            <CaretForwardCircleSharpIcon>
                            </CaretForwardCircleSharpIcon>
                          </n-icon>
                          <n-tag size="small" type="error" v-else>
                            音频未完成
                          </n-tag>
                        </n-col>
                      </n-row>
                      <n-row>
                        <n-col v-if="boardView.duration" :span="24">
                          时长: {{boardView.duration}}
                        </n-col>
                      </n-row>
                      <n-ellipsis :line-clamp="1">
                        {{boardView.content}}
                      </n-ellipsis>
                    </n-card>
                  </n-grid-item>
              </n-grid>
            </n-scrollbar>
          </n-grid-item>
        </n-grid>
        <template #footer>
          <n-space justify="end" style="width: 100%">
            <n-button type="error" @click=" storyBoardView = null; closeDrawer()">关闭</n-button>
            <n-button type="primary" @click="exportJianYin" :loading="jianYingExportLoading">导出剪映草稿</n-button>
          </n-space>
        </template>
      </n-drawer-content>

    </n-drawer>
  </div>
</template>

<script setup lang="ts">
import {NButton, SelectOption} from "naive-ui";
import {computed, onMounted, reactive, ref} from "vue";
import {storyController} from "@/api/story/story.api";
// @ts-ignore
import fileFunction from "@/libs/globalFunction/file"
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
import {
  CaretForwardCircleSharp as CaretForwardCircleSharpIcon
} from '@vicons/ionicons5'
import {ttsDict} from "@/dictionary/ttsDict"
import {creatorDict} from "@/dictionary/creatorDict"
import {sysParamController} from "@/api/controller/sysParamController";

const jianYingExportLoading = ref(false)
const isLocalMode = ref(true)
const drawerWidth = ref(1200)
const statusOption = ref('-1')
const storyBoardView = ref(null)
const mp3Url = ref('')
const audioPlayer = ref(null)
const queryLoading = ref(false)
const {planOptions} = ttsDict()
const {articleType} = creatorDict()
const jianYingDraftPath = ref('')
const statusOptions = ref([
  {
    label: '全部',
    value: '-1'
  },
  {
    label: '已完成',
    value: '1'
  },
  {
    label: '未完成',
    value: '0'
  }
])

const props = defineProps({
  storyId:{
    type: String,
    required: true
  },
  exportJianYingShow:{
    type: Boolean,
    required: true
  },
  closeDrawer: {
    type: Function,
    required: true
  }
})

const staticData = ref({
  totalNum: 0,
  successNum: 0,
  failNum: 0
})

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

onMounted(() => {
  storyBoardView.value = null
  drawerWidth.value = window.innerWidth - 500
  window.addEventListener('resize', ()=>{
    drawerWidth.value = window.innerWidth - 500;
  });
  getStoryBoardView()
  getJianYingDraf()
})

const getJianYingDraf = () =>{
  sysParamController.getParam("jyDraftPath").then((res: any) => {
    if (res.code === 200){
      jianYingDraftPath.value = res.data
    }
  })
}

const exportJianYingForm = ref({
  storyId: "",
  storyName: "",
  draftsPath: "",
  model: '0',
  type: '4',
  scale: 120,
  startLeft : - 240,
  endRight : 240,
  startBottom: -240,
  endTop: 240
})



const getStoryBoardView = () => {
  if (!props.storyId) return
  queryLoading.value = true
  storyController.getStoryBoardView(props.storyId,statusOption.value).then((res: any) => {
    if (res.code == 200){
      storyBoardView.value = res.data
      exportJianYingForm.value.storyName = storyBoardView.value.storyName
      if (storyBoardView.value.storyBoardViews){
        staticData.value.totalNum = storyBoardView.value.storyBoardViews.length
        // 查看已完成和未完成的数量
        let voicePlan = storyBoardView.value.voicePlanType
        if (voicePlan === 'systemVoice'){
          let successNum = storyBoardView.value.storyBoardViews.filter((item: any) => item.voiceUserFileId && item.voiceUserFileId.length> 0  && item.imageUserFileId && item.imageUserFileId.length > 0).length
          staticData.value.successNum = successNum
          staticData.value.failNum = staticData.value.totalNum - successNum
        }else {
          let successNum = storyBoardView.value.storyBoardViews.filter((item: any) =>   item.imageUserFileId && item.imageUserFileId.length > 0).length
          staticData.value.successNum = successNum
          staticData.value.failNum = staticData.value.totalNum - successNum
        }
      }
    }
  }).finally(() => {
    queryLoading.value = false
  })
}

const exportJianYin = () => {
  exportJianYingForm.value.storyId = props.storyId
  jianYingExportLoading.value = true
  storyController.initJianYingDraft(exportJianYingForm.value).then((res: any) => {
    if (res.code === 200) {
      if(isLocalMode){
        window.$message.success('草稿已生成，请打开剪映查看!')
      }else {
        jianYingExportLoading.value = false
        // 准备下载
        let link = document.createElement("a")
        link.style.display = 'none'
        const rowData = {
          userFileId: res.data
        }
        link.href = fileFunction.getDownloadFilePath(rowData)
        document.body.appendChild(link)
        link.click()
      }
    }
  }).finally(() => {
    jianYingExportLoading.value = false
  })
}


const audioPlay = (row:any) => {
  mp3Url.value = fileFunction.getViewFilePathByUserFileId(row.voiceUserFileId)
  audioPlayer.value.pause();
  audioPlayer.value.load();
  audioPlayer.value.play();
}


const audioWholePlay = (userFileId:string) => {
  mp3Url.value = fileFunction.getViewFilePathByUserFileId(userFileId)
  audioPlayer.value.pause();
  audioPlayer.value.load();
  audioPlayer.value.play();
}

const statusSelected = (value: string, option: SelectOption) =>{
  getStoryBoardView()
}

</script>




<style scoped>

</style>
